package com.example.zhibo.common;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // 假设这是前端传来的JSON数据
        String json = "[\n" +
                "  {\n" +
                "    \"field1\": \"value1\",\n" +
                "    \"field2\": 123,\n" +
                "    \"field3\": true\n" +
                "  },\n" +
                "  {\n" +
                "    \"field1\": \"value2\",\n" +
                "    \"field2\": 456,\n" +
                "    \"field3\": false\n" +
                "  }\n" +
                "]";

        Gson gson = new Gson();
        JsonElement[] jsonElements = gson.fromJson(json, JsonElement[].class);

        Set<String> fieldsSet = new LinkedHashSet<>();

        for (JsonElement jsonElement : jsonElements) {
            if (jsonElement.isJsonObject()) {
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
                    String fieldName = entry.getKey();
                    fieldsSet.add(fieldName);
                }
            }
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("fields", fieldsSet);
        resultMap.put("data", json);

        // 将resultMap转为JSON格式的字符串返回给前端
        String resultJson = gson.toJson(resultMap);
        System.out.println(resultJson);
    }
}
